/**
 * WebSocket的二次封装
 */
(function (win) {
	var WSURL = "ws://10.255.254.81:7766/";
	var DEFAILT_OPTION = {
		success: null,
		error: null,
		close: null,
		message: null,
		debug: false
	},
		options = {},
		jsws,
		JSWebSocket = window.WebSocket || window.MozWebSocket,
		/** 事件绑定及处理 */
		bindEvent = function (ws) {
			jsws.onopen = function (e) {
				options.success && options.success.call(ws, e);
			};

			jsws.onclose = function (e) {
				options.close && options.close.call(ws, e);
			};

			jsws.onerror = function (e) {
				options.error && options.error.call(ws, e);
			};

			jsws.onmessage = function (e) {
				if (e && e.data) {
					options.message && options.message.call(ws, e.data);
				}
			};
		};

	win['YSWebSocket'] = function (ops) {
		var _self = this;
		options = $.extend(DEFAILT_OPTION, ops);
		jsws = new JSWebSocket(WSURL);

		jsws && bindEvent(_self);
		_self.handlers = {};

		// 发送数据
		_self.send = function () {
			if (arguments.length) {
				var req = arguments.length > 1 ? arguments[0] : "msg";
				var data = arguments.length > 1 ? arguments[1] : arguments[0];
				var msg = {
					"Url": req,
					"Data": JSON.stringify(data)
				};
				if (JSON && JSON.stringify) {
					msg = JSON.stringify(msg);
					jsws.send(msg);
				}
			}
		};

		_self.close = function () {
			jsws.close();
		};

		_self.regHandler = function (url, callback) {
			_self.handlers[url] = callback;
		};
	};

	if (!win['CefWs']) {
		win.CefWs = new YSWebSocket({
			success: function (e) {

			},
			message: function (e) {
				var msg = $.parseJSON(e);
				if (msg.Url.indexOf('__call__.') != -1) {
					var name = msg.Url.substring('__call__.'.length);
					var call = win[name];
					if (call) {
						var res = call.call(CefWs, msg.Data);
						CefWs.send(name, res);
					}
				} else if (/[0-9a-zA-Z]+\.[0-9a-zA-Z]+/.test(msg.Url)) {
					var call = CefWs.handlers[msg.Url];
					if (call) {
						call.call(CefWs, msg.Data);
					}
				} else if (Object.prototype.toString.call(win[msg.Url]) == '[object Function]') {
					var call = win[msg.Url];
					if (call) {
						call.call(CefWs, msg.Data);
					}
				} else {
					alert(e);
				}
			},
			error: function (e) {
			},
			close: function (e) {
			}
		});
	}
})(window);
